import Vue from 'vue'
import VueRouter from 'vue-router'
// import Layout from '@/views/layout'
// import Login from '@/views/login'
// import NotFound from '@/views/404'
// import Search from '@/views/search'
// import Result from '@/views/search/result'
// import Article from '@/views/article'
// // 二级路由
// import Home from '@/views/layout/home'
// import QA from '@/views/layout/question'
// import Video from '@/views/layout/video'
// import User from '@/views/layout/user'
// import Edit from '@/views/layout/user/edit'
import store from '@/store'
// import Chat from '@/views/layout/user/chat'
const Login = () => import('@/views/login')
const Layout = () => import('@/views/layout')
const NotFound = () => import('@/views/404')
const Home = () => import('@/views/layout/home')
const QA = () => import('@/views/layout/question')
const Video = () => import('@/views/layout/video')
const User = () => import(/* webpackChunkName:"user" */ '@/views/layout/user')
const Search = () => import(/* webpackChunkName:"search" */ '@/views/search')
const UserEdit = () =>
  import(/* webpackChunkName:"user" */ '@/views/layout/user/edit')
const SearchResult = () =>
  import(/* webpackChunkName:"search" */ '@/views/search/result')
const Article = () => import('@/views/article')
const Chat = () =>
  import(/* webpackChunkName:"user" */ '@/views/layout/user/chat')
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: Layout,
    redirect: 'home',
    children: [
      {
        path: 'home',
        component: Home,
        meta: { isKeepLive: true }
      },
      {
        path: 'qs',
        component: QA
      },
      {
        path: 'video',
        component: Video
      },
      {
        path: 'user',
        component: User
      }
    ]
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/search',
    component: Search
  },
  {
    path: '/result',
    component: SearchResult
  },

  {
    path: '/article/:id',
    component: Article
  },
  {
    path: '/user/edit',
    component: UserEdit
  },
  {
    path: '/user/chat',
    component: Chat
  },
  {
    path: '*',
    component: NotFound
  }
]

const router = new VueRouter({
  routes
})

const loginURL = ['/user', '/qs', '/user/edit']
router.beforeEach((to, from, next) => {
  // console.log('从哪来的form', from)
  // console.log('去哪里to', to)
  // next()
  // 1.
  const token = store.state.user.token.token
  // console.log(token)

  if (token) {
    next()
  } else {
    // 没有token
    if (loginURL.some((item) => to.path === item)) {
      // if成立，需要登录
      // next('/login')
      router.push({ path: '/login', query: { back: to.fullPath } })
      // console.log('去哪里to', to)
    } else {
      next()
    }
  }
})

export default router
